<template>
  <el-drawer
      :model-value="drawerVisible"
      title="添加商品"
      :before-close="handleClose"
      size="80%"
      direction="btt"
      class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <el-form :model="form">
        <!-- Product Name -->
        <el-form-item label="产品名" :label-width="formLabelWidth">
          <el-input v-model="form.productName" clearable autocomplete="off"/>
        </el-form-item>
        <!-- Upload Product Cover -->
        <el-form-item label="上传产品封面" :label-width="formLabelWidth">
          <upload ref="uploadComponent" @upload-success="handleUploadSuccess"></upload> <!-- 监听子组件的上传成功事件 -->
        </el-form-item>

        <!-- Brand ID -->
        <el-form-item label="品牌ID" :label-width="formLabelWidth">
          <el-input v-model="form.brandId" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Category ID -->
        <el-form-item label="类别ID" :label-width="formLabelWidth">
          <el-input v-model="form.categoryId" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Model Number -->
        <el-form-item label="型号" :label-width="formLabelWidth">
          <el-input v-model="form.modelNumber" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Unit -->
        <el-form-item label="单位" :label-width="formLabelWidth">
          <el-input v-model="form.unit" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Market Price -->
        <el-form-item label="市场价" :label-width="formLabelWidth">
          <el-input v-model="form.marketPrice" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Selling Price -->
        <el-form-item label="销售价" :label-width="formLabelWidth">
          <el-input v-model="form.sellingPrice" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Cost Price -->
        <el-form-item label="成本价" :label-width="formLabelWidth">
          <el-input v-model="form.costPrice" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Product Description -->
        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.productDescription" clearable autocomplete="off"/>
        </el-form-item>

        <!-- Stock -->
        <el-form-item label="库存" :label-width="formLabelWidth">
          <el-input v-model="form.stock" clearable autocomplete="off"/>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="startSubmitProcess">添加</el-button> <!-- 更改按钮点击事件 -->
      </div>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import {reactive, ref, watch} from 'vue'
import {ElDrawer, ElMessageBox, ElMessage} from 'element-plus'
import upload from '@/components/upload.vue'
//声明一个父组件传递过来的参数，用父子组件通信
defineProps({
  drawerVisible: Boolean,
});
//声明一个监听事件，方便父事件监听
const emit = defineEmits(['update:drawerVisible', 'formSubmitted']);
const formLabelWidth = '80px'


// Form data object
const form = reactive({
  brandId: null,
  categoryId: null,
  productName: "",
  modelNumber: "",
  unit: "",
  marketPrice: null,
  sellingPrice: null,
  costPrice: null,
  productImg: "",
  productDescription: "",
  stock: null
})
import {addProduct} from '@/api/product'
import {headImgStore} from '@/store/tokenStore'

const headImg = headImgStore()
// 方法：开始提交过程，先尝试上传图片
//引用子组件实例
const uploadComponent = ref<InstanceType<typeof upload> | null>(null);
// 方法：开始提交过程，先尝试上传图片
const startSubmitProcess = async () => {
  try {
    if (uploadComponent.value) {
      // 使用Promise等待上传完成
      const uploadPromise = new Promise<void>((resolve, reject) => {
        let unwatch: (() => void) | null = null; // 提前声明unwatch
        // 设置监听器并获取取消监听的方法
          unwatch = watch(
            () => headImg.headImg,
            (newVal) => {
              if (newVal) {
                unwatch(); // 取消监听
                resolve();
              }
            },
            {immediate: true}
        );

        // 调用子组件的manualUpload方法并立即启动上传
        uploadComponent.value.manualUpload();
      });

      await uploadPromise; // 等待上传完成
    }

    // 准备发送给后端的数据
    const formData = {
      ...form,
      productImg: headImg.headImg, // 防止为空时引发问题
      marketPrice: parseInt(form.marketPrice as any) * 100,
      sellingPrice: parseInt(form.sellingPrice as any) * 100,
      costPrice: parseInt(form.costPrice as any) * 100,
      stock: parseInt(form.stock as any, 10)
    };

    await addProduct(formData); // 发送请求添加商品
    ElMessage.success('商品添加成功');
    emit('formSubmitted');
    emit('update:drawerVisible', false);
    resetForm();
  } catch (error) {
    ElMessage.error('商品添加失败,请重试');
    console.error(error); // 记录错误信息，方便调试
  }
}
const handleUploadSuccess = (url: string) => {
};
const handleClose = (done) => {
  ElMessageBox.confirm('确认退出填写？退出后将清空填写内容', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(() => {
    emit('update:drawerVisible', false);
    resetForm()
  }).catch(() => {
    // catch error
  })
}
// Method to reset the form
const resetForm = () => {
  Object.assign(form, {
    brandId: null,
    categoryId: null,
    productName: "",
    modelNumber: "",
    unit: "",
    marketPrice: null,
    sellingPrice: null,
    costPrice: null,
    productImg: "",
    productDescription: "",
    stock: null
  })
  headImg.clearHeadImg()
}

const cancelForm = () => {
  emit('update:drawerVisible', false);
  resetForm()
}
</script>
